package com.hustzp.com.xichuangzhu.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.hustzp.com.xichuangzhu.R;
import com.hustzp.com.xichuangzhu.adapter.LikesPostAdapter;
import com.hustzp.com.xichuangzhu.poetry.CommentListAct;
import com.hustzp.com.xichuangzhu.poetry.NotificationListAct;
import com.hustzp.com.xichuangzhu.poetry.PoetryDetailAct;
import com.hustzp.com.xichuangzhu.poetry.dao.CollectionKindListDao;
import com.hustzp.com.xichuangzhu.poetry.model.LikePost;
import com.hustzp.com.xichuangzhu.poetry.model.Works;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import in.srain.cube.views.loadmore.LoadMoreContainer;
import in.srain.cube.views.loadmore.LoadMoreHandler;
import in.srain.cube.views.loadmore.LoadMoreListViewContainer;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

/**
 * Copyright (C) 2015 The huimai mobile client Project
 * All right reserved.
 *
 * @author: wuzhimin@huimai365.com
 * @date: 2016/5/25 18:38
 * @Description:
 */
public class DayFragment extends Fragment implements LikesPostAdapter.OnPostClickListener, AdapterView.OnItemClickListener {
    private List<LikePost> posts = new ArrayList<>();
    private LikesPostAdapter adapter;
    private ListView lvDayList;
    private PtrFrameLayout mPtrFrameLayout;
    private LoadMoreListViewContainer loadMoreListViewContainer;
    private int page = 1;
    private int pageCount = 15;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_day, container, false);
        ImageButton img_notify = (ImageButton) view.findViewById(R.id.img_notify);
        img_notify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), NotificationListAct.class);
                startActivity(intent);
            }
        });
        lvDayList = (ListView) view.findViewById(R.id.lvDayList);
        lvDayList.setOnItemClickListener(this);
        mPtrFrameLayout = (PtrFrameLayout) view.findViewById(R.id.load_more_list_view_ptr_frame);

        mPtrFrameLayout.setLoadingMinTime(1000);
        mPtrFrameLayout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {

                // here check list view, not content.
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, lvDayList, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                loadPost();
            }
        });


        adapter = new LikesPostAdapter(getActivity(), posts);
        adapter.setOnPostClickListener(this);
        lvDayList.setAdapter(adapter);
        // load more container
        loadMoreListViewContainer = (LoadMoreListViewContainer) view.findViewById(R.id.load_more_list_view_container);
        loadMoreListViewContainer.useDefaultHeader();
        loadMoreListViewContainer.setLoadMoreHandler(new LoadMoreHandler() {
            @Override
            public void onLoadMore(LoadMoreContainer loadMoreContainer) {
                //加载更多操作
                loadPostMore();
            }
        });
        loadPost();
        return view;
    }

    private void loadPost() {
        page = 1;
        loadPosts(page, pageCount);
    }

    private void loadPostMore() {
        page++;
        loadPosts(page, pageCount);
    }

    public void loadPosts(int pageIndex, int pageCount) {
        AVObject channel = AVObject.createWithoutData("objectId", "56ebd926f3609a00545a5a73");
        final AVQuery<LikePost> query = AVQuery.getQuery(LikePost.class);
        query.whereEqualTo("channel", channel);
        query.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
        query.limit(pageCount);
        query.skip((pageIndex - 1) * pageCount);
        query.orderByDescending("createdAt");
        query.include("user");
        query.findInBackground(new FindCallback<LikePost>() {
            @Override
            public void done(List<LikePost> list, AVException e) {
                if (list != null && !list.isEmpty()) {

                    final LinkedHashMap<String, LikePost> tmpPosts = new LinkedHashMap<String, LikePost>();
                    CollectionKindListDao dao = new CollectionKindListDao(getActivity());
                    for (LikePost post : list) {
                        post.setWorks(dao.getWorks(post));
                        tmpPosts.put(post.getObjectId(), post);
                    }

                    // 查询当前登录用户是否已赞
                    if (AVUser.getCurrentUser() != null) {
                        AVQuery likeQuery = AVQuery.getQuery("LikePost");
                        likeQuery.whereEqualTo("user", AVUser.getCurrentUser());
                        likeQuery.whereContainedIn("post", list);
                        likeQuery.findInBackground(new FindCallback<AVObject>() {
                            @Override
                            public void done(List<AVObject> likes, AVException e) {
                                if (likes != null && !likes.isEmpty()) {
                                    for (AVObject like : likes) {
                                        if (tmpPosts.get(like.getAVObject("post").getObjectId()) != null) {
                                            tmpPosts.get(like.getAVObject("post").getObjectId()).setLiked(true);
                                            tmpPosts.get(like.getAVObject("post").getObjectId()).setLikeAVObj(like);
                                        }
                                    }
                                }
                            }
                        });
                    }

                    if (page == 1) {
                        mPtrFrameLayout.refreshComplete();
                        posts.clear();
                    }
                    posts.addAll(tmpPosts.values());
                    adapter.notifyDataSetChanged();
                    loadMoreListViewContainer.loadMoreFinish(false, true);
                } else {
                    page--;
                    loadMoreListViewContainer.loadMoreFinish(false, false);
                }
            }
        });
    }

    @Override
    public void onClick(Works works) {
        Intent intent = new Intent(getActivity(), PoetryDetailAct.class);
        intent.putExtra("from", DayFragment.class.getSimpleName());
        intent.putExtra(Works.class.getSimpleName(), works);
        startActivity(intent);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        LikePost post = (LikePost) parent.getAdapter().getItem(position);
        Intent intent = new Intent(getActivity(), CommentListAct.class);
        intent.putExtra(LikePost.class.getSimpleName(), post);
        startActivity(intent);
    }
}
